package de.dailab.prefgen;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import de.dailab.prefgen.INameMapping.TYPE;


import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class EnumLeaf implements ILeafFactory {

	@Override
	public boolean shouldGenerate(Class type) {
		return type.isEnum();
	}

	@Override
	public Preference generate(Object superObject, Method callingMethod,
			PreferenceActivity context, INameMapping nameMapping) {

		ListPreference list = new ListPreference(context);

		list.setDialogTitle(nameMapping.toHumanReadable(callingMethod,superObject,
				TYPE.TITLE));
		// TODO need Canonical Name
		list.setKey(nameMapping.toHumanReadable(callingMethod,superObject, TYPE.KEY));
		list.setTitle(nameMapping.toHumanReadable(callingMethod,superObject, TYPE.TITLE));
		list.setSummary(nameMapping.toHumanReadable(callingMethod, superObject,TYPE.DESCRIPTION));
		list.setPersistent(false);
		list.setOnPreferenceChangeListener(new OnLeafPrefernceChangedListener(
				superObject, callingMethod, nameMapping));
		try {

			Object obj = callingMethod.invoke(superObject, null);

			Class type = callingMethod.getReturnType();

			Object[] enumConstants = type.getEnumConstants();

			String[] entries = new String[enumConstants.length];
			String[] keys = new String[enumConstants.length];

			for (int i = 0; i < entries.length; i++) {
				entries[i] = enumConstants[i].toString();
			}
			
			list.setEntries(entries);
			list.setEntryValues(entries);
			
			Enum enu = (Enum) callingMethod.invoke(superObject, null);
			
			//if there is no Value set
			if (enu!=null)
			list.setValueIndex(enu.ordinal());

			return list;

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

}
